import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sph_driver/AppConfig/ShowDialog.dart';
import 'package:sph_driver/AppConfig/StringEncapsulation.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/LocalStorage.dart';
import '../../Authentication/AuthenticationModel/CarCardModel.dart';
import '../../Authentication/AuthenticationModel/DriverCardModel.dart';
import '../../http/api.dart';
import '../../l10n/messages.dart';
import 'package:image/image.dart' as img;

import '../EditInformation/EditCarCard.dart';
import '../EditInformation/ShowImageView.dart';


class AddTrailerCardView extends StatefulWidget {
  const AddTrailerCardView({super.key, required this.dataMap});
  final Map dataMap;
  @override
  State<AddTrailerCardView> createState() => _AddTrailerCardViewState();
}

class _AddTrailerCardViewState extends State<AddTrailerCardView> {
  List titleList=["车牌号","车牌颜色","车长车型","车辆类型","车辆识别代号","使用性质","注册日期","发证日期","发证机关","车辆所有人",
    "档案编号","能源类型","总质量(Kg)","整备质量(Kg)","核定载重质量(Kg)","年审有效期至","强制报废截止日","证芯编号","外廓车长","外廓车宽","外廓车高"];
  List dataList =["","","","","","","","","","","","","","", "","","","","","",""];
  Map energyMap={"天然气":"E","混合油":"D","电":"C","柴油":"B","汽油":"A","其他":"Z"};
  late String ChooseIndex="";
  final ImagePicker picker = new ImagePicker();
//用户本地图片
  File? _userImage;//存放获取到的本地路径
  File? _userImage2;//存放获取到的本地路径
  File? _userImage3;//存放获取到的本地路径
  int oneCheck =0;
  String cardImgStr="";
  String cardImgStr2="";
  Map dataMap={};
  String getfrontPath="";
  String getbackPath="";
  String carLength="";
  String carType ="";
  String carcolor="";
  bool isAnotherpage=false;
  bool isEdit=true;
  bool isShowError=false;
  TextEditingController _nametextEditingController = TextEditingController();
  CarCardModel cardModel=CarCardModel(DriverPic: "", DriverPic2: "", CarNum: "", CarColor: "",
      LengthWeight: "", CarStyle: "", KnowNum: "", UseStyle: "", AddTime: "", OfficeTime: "",
      CardOfficeName: "", CarUser: "", MessageNum: "", OilStyle: "", AllWeight: "",
      UpWeight: "", UseWeight: "", YearEndTime: "", CarEndTime: "", CardNum: "", OutLength: "",
      OutWidth: "", OutHeight: "");
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.dataMap['trailerDrivingLicenseInfo']!=null) {
      isEdit=false;
      carcolor = widget.dataMap['trailerDrivingLicenseInfo']['vehicleNumColor'] == "1" ? "蓝色" : widget
          .dataMap['trailerDrivingLicenseInfo']['vehicleNumColor'] == "2" ? "黄色" : widget
          .dataMap['trailerDrivingLicenseInfo']['vehicleNumColor'] == "5" ? "绿色" : widget
          .dataMap['trailerDrivingLicenseInfo']['vehicleNumColor'] == "93" ? "黄绿色" : "其他";
      dataList = [
        widget.dataMap['trailerDrivingLicenseInfo']['vehicleNum'],
        "黄色","",
        // widget.dataMap['trailerDrivingLicenseInfo']['vehicleLength']
        //     +
        //     widget.dataMap['trailerDrivingLicenseInfo']['vehicleModel'],
        widget.dataMap['trailerDrivingLicenseInfo']['vehicleType'],
        widget.dataMap['trailerDrivingLicenseInfo']['vin'],
        widget
            .dataMap['trailerDrivingLicenseInfo']['useCharacter'],
        widget
            .dataMap['trailerDrivingLicenseInfo']['registerDate'],
        widget.dataMap['trailerDrivingLicenseInfo']['issueDate'],
        widget
            .dataMap['trailerDrivingLicenseInfo']['issuingOrganizations'],
        widget.dataMap['trailerDrivingLicenseInfo']['owner'],
        widget.dataMap['trailerDrivingLicenseInfo']['fileNum'],
        widget
            .dataMap['trailerDrivingLicenseInfo']['vehicleEnergyType'],
        widget.dataMap['trailerDrivingLicenseInfo']['grossMass'],
        widget.dataMap['trailerDrivingLicenseInfo']['grossMass'],
        widget
            .dataMap['trailerDrivingLicenseInfo']['vehicleTonnage'],
        widget
            .dataMap['trailerDrivingLicenseInfo']['expiryDate'],
        widget.dataMap['trailerDrivingLicenseInfo']['scrapDate'],
        widget
            .dataMap['trailerDrivingLicenseInfo']['certificateCoreNum'],
        widget.dataMap['trailerDrivingLicenseInfo']['overallLength'],
        widget
            .dataMap['trailerDrivingLicenseInfo']['overallWide'],
        widget
            .dataMap['trailerDrivingLicenseInfo']['overallHigh']
      ];
      if (widget.dataMap['trailerDrivingLicenseInfo'] != null && widget
          .dataMap['trailerDrivingLicenseInfo']['frontPath'] !=
          null) {
        getfrontPath =
        widget.dataMap['trailerDrivingLicenseInfo']['frontPath'];
        getbackPath =
        widget.dataMap['trailerDrivingLicenseInfo']['backPath'];
      }
    }
  }
  void uploadOcrAction()  async{
    String? drvId =await UserIdManager.getUserID();
    LoadingDialog.show(context);
    if (cardImgStr!=""&&cardImgStr2!="")
      print(cardImgStr);
    print(cardImgStr2);
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) async {
          options.headers["satoken"] = await TokenManager.getToken();
          return handler.next(options);
        }
    ));
    dio
        .post(
      MyServiceUrl.header+'api/system/dev/ocr/doOcr',
      data: {
        "typeKey":"fleet_"+drvId!,
        "type": "VL",
        "frontFileFormat": "jpg",
        "frontData": cardImgStr,
        "backFileFormat":"jpg",
        "backData": cardImgStr2,
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),

    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        LoadingDialog.hide(context);
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          BrnToast.show("识别成功", context);
          setState(() {
            dataMap=jsonMap['data']['result'];
            RegExp regExp = RegExp(r'(\d{4})年(\d{2})月');
            Match match = regExp.firstMatch(dataMap['inspectionRecord']) as Match;
            String? year = match.group(1);
            String? month = match.group(2);
            String inspectionRecord=year!+"-"+month!;
            print(inspectionRecord);
            String note="";
            if(dataMap['note'].contains("强制报废期止：")){
              note=dataMap['note'].replaceAll("强制报废期止：", "");
            }
            setState(() {
              dataList=[dataMap['vclN'],"","",dataMap['vcltype'],dataMap['vin'],dataMap['natureOfUsage'],dataMap['regTime'],
                dataMap['licensedateOfissue'],dataMap['issuingAuthority'],dataMap['ownerName'],dataMap['recordId'],getEnergyType(dataMap['inspectionRecord'], energyMap),dataMap['approveTon'],
                dataMap['enTn'].replaceAll("kg", ""),dataMap['loadTon'],inspectionRecord,note,dataMap['barCode'],dataMap['overallDimen'].split('×')[0]+"mm"
                ,dataMap['overallDimen'].split('×')[1]+"mm",dataMap['overallDimen'].split('×')[2]];
              getfrontPath=jsonMap['data']['frontPath'];
              getbackPath=jsonMap['data']['backPath'];
            });
            if (isDateExpired(dataMap['expiryDate'])) {
              isAnotherpage=true;
            }
          });

        }else{
          BrnToast.show(
            jsonMap['msg'],
            context,
            duration: BrnDuration.short,
          );
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }

  String imageToBase64(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    String base64String = base64Encode(Uint8List.fromList(imageBytes));

    return base64String;
  }


  void printImageMemorySize(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    print('Original Image Memory Size: ${imageBytes.length} bytes');
  }

  Future<void> compressImage(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

    // Adjust the quality and size as needed
    img.Image compressedImage = img.copyResize(image, width: 1024);

    List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

    // Create a new File for the compressed image
    File compressedFile = File('${imageFile.path}_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);

    print('Compressed Image Size: ${compressedBytes.length} bytes');

    convertToBase64(compressedFile);
  }

  Future<void> convertToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    String base64String = base64Encode(imageBytes);

    oneCheck==1?
    cardImgStr =base64String
        :cardImgStr2 =base64String;
    uploadOcrAction();

  }
  @override
  Widget build(BuildContext context) {
    var messages = AppLocalizations.of(context)!;
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: Text("添加挂车",style: TextStyle(fontWeight: FontWeight.w300),),
        centerTitle: true,
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.pop(context,"success"),
        ),
      ),
      body: Column(
        children: [
          Expanded(child:
          ListView(
            children: [
              Container(
                color: Colors.white,
                height: 140.h,
                child:Column(
                  // crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 8.h,),
                    Row(
                      children: [
                        SizedBox(width: 18.w,),
                        Text("上传行驶证(必填)",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                      ],
                    ),
                    SizedBox(height: 8.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,

                      children: [
                        GestureDetector(
                          child:
                          getfrontPath!=""&&_userImage==null?
                          Stack(
                            children: [
                              Container(
                                height: 90.h,
                                width: 150.w,
                                child:   Image.network(MyServiceUrl.imgHeader+getfrontPath ,height: 90.h,width: 150.w,fit: BoxFit.cover,),
                              ),
                              if(isEdit)
                              Center(
                                child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                              ),
                            ],
                            alignment: Alignment.center,
                          )
                              :getfrontPath!=""&&_userImage!=null?
                          Stack(

                            children: [

                              Container(
                                height: 90.h,
                                width: 150.w,
                                child: Image.file(_userImage!,height: 90.h,width: 150.w,fit: BoxFit.cover,) ,
                              ),
                              if(isEdit)
                                Center(
                                  child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                                ),
                            ],
                            alignment: Alignment.center,
                          )
                              :
                          Image.asset("lib/Images/Authentication/上传行驶证主页.png" ,height: 90.h,width: 150.w,),
                          onTap: () async{
                            if(isEdit==false){
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => ShowImageViewer( (MyServiceUrl.imgHeader+getfrontPath).toString()),
                                ),
                              );
                            }else {
                              showModalBottomSheet(context: context,
                                  builder: (BuildContext context) {
                                    return Container(
                                      decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(10))),
                                      child:
                                      Stack(

                                        children: [

                                          Column(
                                            mainAxisSize: MainAxisSize.min,
                                            mainAxisAlignment: MainAxisAlignment
                                                .center,

                                            children: [

                                              Row(
                                                mainAxisAlignment: MainAxisAlignment
                                                    .end,
                                                children: [
                                                  IconButton(onPressed: () {
                                                    Navigator.of(context)
                                                        .pop();
                                                  },
                                                      icon: Icon(Icons.close,
                                                        color: MyColors
                                                            .textColor,)),
                                                ],
                                              ),
                                              Text(messages["示例"],
                                                style: TextStyle(
                                                    color: Colors.black,
                                                    fontSize: 14.sp),),
                                              SizedBox(height: 8.h,),
                                              Image.asset(
                                                'lib/Images/Authentication/行驶证主页示例图.png',
                                                width: 2270.w,
                                                height: 145.h,),
                                              SizedBox(height: 8.h,),
                                              Text(messages["请按照示例上传"],
                                                style: TextStyle(
                                                    color: Color.fromRGBO(
                                                        102, 102, 102, 1)),),
                                              Text(
                                                messages["模糊、遮挡会导致证件无法识别，认证不通过"],
                                                style: TextStyle(
                                                    color: Color.fromRGBO(
                                                        102, 102, 102, 1)),),
                                              SizedBox(height: 8.h,),
                                              Text(messages["上传照片"],
                                                style: TextStyle(
                                                    color: Colors.black,
                                                    fontWeight: FontWeight
                                                        .w600,
                                                    fontSize: 18.sp),),
                                              SizedBox(height: 10.h,),
                                              Row(
                                                children: [
                                                  SizedBox(width: 38.w,),
                                                  GestureDetector(
                                                    child: Column(
                                                      children: [
                                                        Image.asset(
                                                          "lib/Images/Authentication/相册icon.png",
                                                          width: 35.w,
                                                          height: 35.h,),
                                                        Text(messages["相册"],
                                                          style: TextStyle(
                                                              color: Colors
                                                                  .black),),

                                                      ],

                                                    ),
                                                    onTap: () async {
                                                      Navigator.of(context)
                                                          .pop();
                                                      final pickedFile = await picker
                                                          .pickImage(
                                                          source: ImageSource
                                                              .gallery);

                                                      if (pickedFile !=
                                                          null) {
                                                        setState(() {
                                                          oneCheck = 1;
                                                          _userImage = File(
                                                              pickedFile
                                                                  .path);
                                                          printImageMemorySize(
                                                              _userImage!);
                                                          print(_userImage);
                                                          compressImage(
                                                              _userImage!);
                                                        });
                                                      }
                                                    },
                                                  ),

                                                  SizedBox(width: 38.w,),
                                                  GestureDetector(
                                                    child: Column(
                                                      children: [
                                                        Image.asset(
                                                          "lib/Images/Authentication/拍照icon.png",
                                                          width: 35.w,
                                                          height: 35.h,),
                                                        Text(messages["拍照"],
                                                          style: TextStyle(
                                                              color: Colors
                                                                  .black),),

                                                      ],

                                                    ),
                                                    onTap: () async {
                                                      Navigator.of(context)
                                                          .pop();
                                                      final pickedFile = await picker
                                                          .pickImage(
                                                          source: ImageSource
                                                              .camera);

                                                      if (pickedFile !=
                                                          null) {
                                                        setState(() {
                                                          oneCheck = 1;
                                                          _userImage = File(
                                                              pickedFile
                                                                  .path);
                                                          printImageMemorySize(
                                                              _userImage!);
                                                          print(_userImage);
                                                          compressImage(
                                                              _userImage!);
                                                        });
                                                      }
                                                    },
                                                  ),

                                                ],
                                              ),
                                              SizedBox(height: 30.h,),
                                            ],
                                          ),
                                        ],

                                      ),
                                    );
                                  });
                            }
                          },
                        ),
                        SizedBox(width: 20.w,),
                        GestureDetector(
                          child:
                          getbackPath!=""&&_userImage2==null?
                          Stack(
                            children: [
                              Container(
                                height: 90.h,
                                width: 150.w,
                                child:   Image.network(MyServiceUrl.imgHeader+getbackPath ,height: 90.h,width: 150.w,fit: BoxFit.cover,),
                              ),
                              if(isEdit)
                              Center(
                                child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                              ),
                            ],
                            alignment: Alignment.center,
                          )
                              :getbackPath!=""&&_userImage2!=null?
                          Stack(

                            children: [

                              Container(
                                height: 90.h,
                                width: 150.w,
                                child: Image.file(_userImage2!,height: 90.h,width: 150.w,fit: BoxFit.cover,) ,
                              ),
                              if(isEdit)
                                Center(
                                  child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                                ),
                            ],
                            alignment: Alignment.center,
                          ):
                          Image.asset("lib/Images/Authentication/上传行驶证副页.png" ,height: 90.h,width: 150.w,),
                          onTap: () async{
                            if(isEdit==false){
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => ShowImageViewer( (MyServiceUrl.imgHeader+getbackPath).toString()),
                                ),
                              );
                            }else {
                              showModalBottomSheet(context: context,
                                  builder: (BuildContext context) {
                                    return Container(
                                      decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(10))),
                                      child:
                                      Stack(
                                        children: [
                                          Column(
                                            mainAxisSize: MainAxisSize.min,
                                            mainAxisAlignment: MainAxisAlignment
                                                .center,
                                            children: [

                                              Row(
                                                mainAxisAlignment: MainAxisAlignment
                                                    .end,
                                                children: [
                                                  IconButton(onPressed: () {
                                                    Navigator.of(context).pop();
                                                  },
                                                      icon: Icon(Icons.close,
                                                        color: MyColors
                                                            .textColor,)),
                                                ],
                                              ),
                                              Text(messages["示例"],
                                                style: TextStyle(
                                                    color: Colors.black),),
                                              SizedBox(height: 8.h,),
                                              Image.asset(
                                                'lib/Images/Authentication/行驶证副页示例图.png',
                                                width: 2270.w, height: 145.h,),
                                              SizedBox(height: 8.h,),
                                              Text(messages["请按照示例上传"],
                                                style: TextStyle(
                                                    color: Color.fromRGBO(
                                                        102, 102, 102, 1)),),
                                              Text(
                                                messages["模糊、遮挡会导致证件无法识别，认证不通过"],
                                                style: TextStyle(
                                                    color: Color.fromRGBO(
                                                        102, 102, 102, 1)),),
                                              SizedBox(height: 8.h,),
                                              Text(messages["上传照片"],
                                                style: TextStyle(
                                                    color: Colors.black,
                                                    fontWeight: FontWeight.w600,
                                                    fontSize: 18.sp),),
                                              SizedBox(height: 10.h,),
                                              Row(
                                                children: [
                                                  SizedBox(width: 38.w,),
                                                  GestureDetector(
                                                    child: Column(
                                                      children: [
                                                        Image.asset(
                                                          "lib/Images/Authentication/相册icon.png",
                                                          width: 35.w,
                                                          height: 35.h,),
                                                        Text(messages["相册"],
                                                          style: TextStyle(
                                                              color: Colors
                                                                  .black),),
                                                      ],
                                                    ),
                                                    onTap: () async {
                                                      Navigator.of(context)
                                                          .pop();
                                                      final pickedFile = await picker
                                                          .pickImage(
                                                          source: ImageSource
                                                              .gallery);

                                                      if (pickedFile != null) {
                                                        setState(() {
                                                          oneCheck = 2;
                                                          _userImage2 = File(
                                                              pickedFile.path);
                                                          printImageMemorySize(
                                                              _userImage2!);
                                                          print(_userImage2);
                                                          compressImage(
                                                              _userImage2!);
                                                        });
                                                      }
                                                    },
                                                  ),
                                                  SizedBox(width: 38.w,),
                                                  GestureDetector(
                                                    child: Column(
                                                      children: [
                                                        Image.asset(
                                                          "lib/Images/Authentication/拍照icon.png",
                                                          width: 35.w,
                                                          height: 35.h,),
                                                        Text(messages["拍照"],
                                                          style: TextStyle(
                                                              color: Colors
                                                                  .black),),
                                                      ],
                                                    ),
                                                    onTap: () async {
                                                      Navigator.of(context)
                                                          .pop();
                                                      final pickedFile = await picker
                                                          .pickImage(
                                                          source: ImageSource
                                                              .camera);

                                                      if (pickedFile != null) {
                                                        setState(() {
                                                          oneCheck = 2;
                                                          _userImage2 = File(
                                                              pickedFile.path);
                                                          printImageMemorySize(
                                                              _userImage2!);
                                                          print(_userImage2);
                                                          compressImage(
                                                              _userImage2!);
                                                        });
                                                      }
                                                    },
                                                  ),
                                                ],
                                              ),
                                              SizedBox(height: 20.h,),
                                            ],
                                          ),
                                        ],
                                      ),
                                    );
                                  });
                            }
                          },
                        ),
                      ],
                    ),
                  ],
                ) ,
              ),
              if(isAnotherpage)
                SizedBox(height: 8.h,),
              if(isAnotherpage)
                Container(
                  color: Colors.white,
                  height: 88.h,
                  padding: EdgeInsets.only(top: 8.h),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      SizedBox(width: 2.w,),
                      Column(

                        children: [
                          SizedBox(height: 10.h,),
                          Row(

                            children: [
                              Image.asset("lib/Images/Authentication/橙色感叹号warning.png",width: 20.w,height: 20.h,),
                              SizedBox(width:4.w,),
                              Text("上传副页背面",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85)),),
                              SizedBox(width:64.w,),
                            ],
                          ),
                          Text("检测到您的年审有效期已过期，\n请上传行驶证副页背面",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85),fontSize: 12.sp),),


                        ],
                      ),
                      GestureDetector(
                        child:
                        _userImage3!=null?
                        Stack(

                          children: [

                            Container(
                              height: 65.h,
                              width: 102.w,

                              child: Image.file(_userImage3!,height: 65.h,width: 102.w,fit: BoxFit.cover,) ,
                            ),
                            Center(
                              child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                            ),
                          ],
                          alignment: Alignment.center,
                        )

                            :
                        Image.asset("lib/Images/Authentication/上传行驶证副页的背面.png" ,height: 65.h,width: 102.w,),
                        onTap: () async{
                          showModalBottomSheet(context: context, builder: (BuildContext context) {
                            return Container(
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.all(Radius.circular(10))),
                              child:
                              Stack(

                                children: [

                                  Column(
                                    mainAxisSize: MainAxisSize.min,
                                    mainAxisAlignment:MainAxisAlignment.center,

                                    children:[

                                      SizedBox(height: 8.h,),
                                      Row(
                                        mainAxisAlignment:MainAxisAlignment.end,
                                        children: [
                                          IconButton(onPressed: (){
                                            Navigator.of(context).pop();
                                          }, icon:Icon(Icons.close,color: MyColors.textColor,)),
                                        ],
                                      ),
                                      Text(messages["示例"],style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                      SizedBox(height: 8.h,),
                                      Image.asset('lib/Images/Authentication/行驶证副页示例图.png',width: 2270.w,height: 145.h,),


                                      SizedBox(height: 8.h,),
                                      Text(messages["请按照示例上传"],style: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),),
                                      Text(messages["模糊、遮挡会导致证件无法识别，认证不通过"],style: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),),
                                      SizedBox(height: 8.h,),
                                      Text(messages["上传照片"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                                      SizedBox(height: 18.h,),
                                      Row(
                                        children: [
                                          SizedBox(width: 38.w,),
                                          GestureDetector(
                                            child:   Column(
                                              children: [
                                                Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                                                Text(messages["相册"],style: TextStyle(color: Colors.black),),

                                              ],

                                            ),
                                            onTap: ()async{
                                              Navigator.of(context).pop();
                                              final pickerImages = await picker.pickImage(source: ImageSource.gallery);
                                              if(mounted){
                                                setState(() {
                                                  oneCheck=1;
                                                  if(pickerImages != null){
                                                    _userImage3 = File(pickerImages.path);
                                                    print('你选择的本地路径是：${_userImage3.toString()}');

                                                  }else{
                                                    print('没有照片可以选择');
                                                  }
                                                });
                                              };
                                            },
                                          ),

                                          SizedBox(width: 38.w,),
                                          GestureDetector(
                                            child: Column(
                                              children: [
                                                Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                                                Text(messages["拍照"],style: TextStyle(color: Colors.black),),

                                              ],

                                            ),
                                            onTap: ()async{
                                              Navigator.of(context).pop();
                                              final pickerImages = await picker.pickImage(source: ImageSource.camera);
                                              if(mounted){
                                                setState(() {
                                                  oneCheck=1;
                                                  if(pickerImages != null){
                                                    _userImage3 = File(pickerImages.path);
                                                    print('你选择的本地路径是：${_userImage3.toString()}');

                                                  }else{
                                                    print('没有照片可以选择');
                                                  }
                                                });
                                              };
                                            },
                                          ),

                                        ],
                                      ),
                                      SizedBox(height: 20.h,),
                                    ],

                                  ),

                                ],

                              ),
                            );


                          });

                        },
                      ),

                      SizedBox(width: 2.w,),
                    ],
                  ),
                ),
              SizedBox(height: 8.h,),
              Container(
                margin: EdgeInsets.only(left: 8.w,right: 8.w),
                height: 920.h,
                child:  ListView.separated(
                    physics: NeverScrollableScrollPhysics(),
                    itemCount:21,
                    separatorBuilder: (BuildContext context, int index) {
                      return Container(
                        // 这里使用 Divider 作为分隔符s
                        color: Color.fromRGBO(248, 248, 248, 1),
                        height:(index==1||index==2)? 0:  8.h,  // 分隔符的高度
                      );
                    },
                    itemBuilder:(context, index) {
                      return Padding(padding:

                      EdgeInsets.only(left: 8.w,right: 8.w),
                        child:  GestureDetector(
                            child: Container(height:(index==1||index==2)? 0: 40.h,

                              decoration: BoxDecoration(
                                  border: Border.all(
                                    color:isShowError==true&&dataList[index]==''? Colors.red:Colors.white, // 边框颜色
                                    width: 0.5, // 边框宽度
                                  ),
                                  color: Colors.white,
                                  borderRadius: BorderRadius.all(Radius.circular(10))),
                              child: (index==1||index==2)?SizedBox(height: 0,):
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Row(
                                    children: [
                                      SizedBox(width: 8.h,),
                                      Text(titleList[index],style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                    ],
                                  ),
                                  Row(
                                    children: [

                                      Container(
                                        width: screenSize.width-180.w,
                                        child: Text(dataList[index].toString(),textAlign: TextAlign.right,style: TextStyle(color:Colors.black,overflow:TextOverflow.ellipsis,fontSize: 14.sp ),),
                                      ),
                                      isEdit?
                                      Icon(Icons.arrow_forward_ios,color: MyColors.authTipColor,):SizedBox(width: 10.w,),
                                    ],
                                  ),



                                ],
                              ),
                            ),
                            onTap: () async {
                              if (isEdit) {
                                if (index == 6) {
                                  final result = await showModalBottomSheet(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return dataTimeSheet(
                                      );
                                    },
                                  );

                                  if (result != null) {
                                    String mounth = "";
                                    String day = "";

                                    setState(() {
                                      if (result[1]
                                          .toString()
                                          .length == 1) {
                                        mounth = result[1].toString().padLeft(
                                            2, '0');
                                      } else {
                                        mounth = result[1].toStringAsFixed(0);
                                      }
                                      if (result[2]
                                          .toString()
                                          .length == 1) {
                                        day = result[2].toString().padLeft(
                                            2, '0');
                                      } else {
                                        day = result[2].toStringAsFixed(0);
                                      }

                                      String Time = result[0].toString() + "-" +
                                          mounth + "-" + day;
                                      dataList[6] = Time;
                                      cardModel.AddTime = Time;
                                      _nametextEditingController.text =
                                          cardModel.AddTime;
                                    });
                                  }
                                } else if (index == 1) {
                                  final result = await showModalBottomSheet(
                                      context: context,

                                      enableDrag: false,
                                      builder: (BuildContext context) {
                                        return ChooseColorsheet(
                                          colorStr: dataList[1],);
                                      }
                                  );
                                  if (result != null) {
                                    setState(() {
                                      dataList[1] = result[0];
                                    });
                                  }
                                } else if (index == 2) {
                                  final result = await showModalBottomSheet(
                                      context: context,
                                      isDismissible: false,
                                      // 设置为 false，点击外部区域不关闭
                                      enableDrag: false,
                                      builder: (BuildContext context) {
                                        return CheckCarTypeSheet(
                                          editString: dataList[2],);
                                      }
                                  );
                                  if (result != null) {
                                    setState(() {
                                      carType = result[1];
                                      carLength = result[0];
                                      dataList[2] = result[0] + "," + result[1];
                                    });
                                  }
                                } else if (index == 7) {
                                  final result = await showModalBottomSheet(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return dataTimeSheet(
                                      );
                                    },
                                  );

                                  if (result != null) {
                                    String mounth = "";
                                    String day = "";

                                    setState(() {
                                      if (result[1]
                                          .toString()
                                          .length == 1) {
                                        mounth = result[1].toString().padLeft(
                                            2, '0');
                                      } else {
                                        mounth = result[1].toStringAsFixed(0);
                                      }
                                      if (result[2]
                                          .toString()
                                          .length == 1) {
                                        day = result[2].toString().padLeft(
                                            2, '0');
                                      } else {
                                        day = result[2].toStringAsFixed(0);
                                      }

                                      String Time = result[0].toString() + "-" +
                                          mounth + "-" + day;
                                      dataList[7] = Time;
                                      cardModel.OfficeTime = Time;
                                      _nametextEditingController.text =
                                          cardModel.OfficeTime;
                                    });
                                  }
                                } else if (index == 11) {
                                  final result = await showModalBottomSheet(
                                      context: context,
                                      // isDismissible: false, // 设置为 false，点击外部区域不关闭
                                      enableDrag: false,
                                      builder: (BuildContext context) {
                                        return chooseEnergySheet(
                                          energyType: dataList[11],);
                                      }
                                  );
                                  if (result != null) {
                                    setState(() {
                                      dataList[11] = result[0];
                                    });
                                  }
                                } else if (index == 15) {
                                  final result = await showModalBottomSheet(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return dataTimeSheet(
                                      );
                                    },
                                  );

                                  if (result != null) {
                                    String mounth = "";
                                    String day = "";

                                    setState(() {
                                      if (result[1]
                                          .toString()
                                          .length == 1) {
                                        mounth = result[1].toString().padLeft(
                                            2, '0');
                                      } else {
                                        mounth = result[1].toStringAsFixed(0);
                                      }
                                      if (result[2]
                                          .toString()
                                          .length == 1) {
                                        day = result[2].toString().padLeft(
                                            2, '0');
                                      } else {
                                        day = result[2].toStringAsFixed(0);
                                      }

                                      String Time = result[0].toString() + "-" +
                                          mounth + "-" + day;
                                      dataList[15] = Time;
                                      cardModel.YearEndTime = Time;
                                      _nametextEditingController.text =
                                          cardModel.YearEndTime;
                                    });
                                  }
                                } else if (index == 16) {
                                  final result = await showModalBottomSheet(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return dataTimeSheet(
                                      );
                                    },
                                  );

                                  if (result != null) {
                                    String mounth = "";
                                    String day = "";

                                    setState(() {
                                      if (result[1]
                                          .toString()
                                          .length == 1) {
                                        mounth = result[1].toString().padLeft(
                                            2, '0');
                                      } else {
                                        mounth = result[1].toStringAsFixed(0);
                                      }
                                      if (result[2]
                                          .toString()
                                          .length == 1) {
                                        day = result[2].toString().padLeft(
                                            2, '0');
                                      } else {
                                        day = result[2].toStringAsFixed(0);
                                      }

                                      String Time = result[0].toString() + "-" +
                                          mounth + "-" + day;
                                      dataList[16] = Time;
                                      cardModel.CarEndTime = Time;
                                      _nametextEditingController.text =
                                          cardModel.CarEndTime;
                                    });
                                  }
                                } else {
                                  _nametextEditingController.text =
                                  dataList[index];
                                  showModalBottomSheet(
                                      isDismissible: false,
                                      context: context,

                                      builder: (BuildContext context) {
                                        return Container(

                                          color: Color.fromRGBO(
                                              255, 255, 255, 1),
                                          child: Column(

                                            children: [

                                              SizedBox(height: 8.h,),
                                              Row(
                                                mainAxisAlignment: MainAxisAlignment
                                                    .spaceBetween,
                                                children: [
                                                  TextButton(onPressed: () {
                                                    Navigator.of(context)
                                                        .pop();
                                                    setState(() {
                                                      if (index == 0) {
                                                        cardModel.CarNum =
                                                        dataList[index];
                                                      } else if (index == 1) {
                                                        cardModel
                                                            .CarColor =
                                                        dataList[index];
                                                      } else if (index == 2) {
                                                        cardModel.LengthWeight =
                                                        dataList[index];
                                                      } else if (index == 3) {
                                                        cardModel
                                                            .CarStyle =
                                                        dataList[index];
                                                      } else if (index == 4) {
                                                        cardModel.KnowNum =
                                                        dataList[index];
                                                      } else if (index == 5) {
                                                        cardModel
                                                            .UseStyle =
                                                        dataList[index];
                                                      } else if (index == 6) {
                                                        cardModel.AddTime =
                                                        dataList[index];
                                                      } else if (index == 7) {
                                                        cardModel.OfficeTime =
                                                        dataList[index];
                                                      } else if (index == 8) {
                                                        cardModel
                                                            .CardOfficeName =
                                                        dataList[index];
                                                      }
                                                      else if (index == 9) {
                                                        cardModel.CarUser =
                                                        dataList[index];
                                                      }
                                                      else if (index == 10) {
                                                        cardModel.MessageNum =
                                                        dataList[index];
                                                      } else if (index == 11) {
                                                        cardModel.OilStyle =
                                                        dataList[index];
                                                      } else if (index == 12) {
                                                        cardModel.AllWeight =
                                                        dataList[index];
                                                      } else if (index == 13) {
                                                        cardModel.UpWeight =
                                                        dataList[index];
                                                      } else if (index == 14) {
                                                        cardModel.UseWeight =
                                                        dataList[index];
                                                      } else if (index == 17) {
                                                        cardModel.CardNum =
                                                        dataList[index];
                                                      } else if (index == 18) {
                                                        cardModel.OutLength =
                                                        dataList[index];
                                                      } else if (index == 19) {
                                                        cardModel.OutWidth =
                                                        dataList[index];
                                                      } else if (index == 20) {
                                                        cardModel.OutHeight =
                                                        dataList[index];
                                                      }
                                                      _nametextEditingController
                                                          .text =
                                                      dataList[index];
                                                    });
                                                  },
                                                      child: Text(
                                                        messages["取消"],
                                                        style: TextStyle(
                                                            color: Colors.black,
                                                            fontSize: 14.sp),)),
                                                  Text(
                                                    titleList[index] + "输入",
                                                    style: TextStyle(
                                                        color: Colors.black,
                                                        fontSize: 16.sp,
                                                        fontWeight: FontWeight
                                                            .w600),),
                                                  TextButton(onPressed: () {
                                                    Navigator.of(context).pop();

                                                    setState(() {
                                                      if (index == 0) {
                                                        dataList[index] =
                                                            cardModel.CarNum;
                                                      } else if (index == 1) {
                                                        dataList[index] =
                                                            cardModel.CarColor;
                                                      } else if (index == 2) {
                                                        dataList[index] =
                                                            cardModel
                                                                .LengthWeight;
                                                      } else if (index == 3) {
                                                        dataList[index] =
                                                            cardModel.CarStyle;
                                                      } else if (index == 4) {
                                                        dataList[index] =
                                                            cardModel.KnowNum;
                                                      } else if (index == 5) {
                                                        dataList[index] =
                                                            cardModel.UseStyle;
                                                      } else if (index == 6) {
                                                        dataList[index] =
                                                            cardModel.AddTime;
                                                      }
                                                      else if (index == 7) {
                                                        dataList[index] =
                                                            cardModel
                                                                .OfficeTime;
                                                      } else if (index == 8) {
                                                        dataList[index] =
                                                            cardModel
                                                                .CardOfficeName;
                                                      } else if (index == 9) {
                                                        dataList[index] =
                                                            cardModel.CarUser;
                                                      } else if (index == 10) {
                                                        dataList[index] =
                                                            cardModel
                                                                .MessageNum;
                                                      } else if (index == 11) {
                                                        dataList[index] =
                                                            cardModel.OilStyle;
                                                      } else if (index == 12) {
                                                        dataList[index] =
                                                            cardModel.AllWeight;
                                                      } else if (index == 13) {
                                                        dataList[index] =
                                                            cardModel.UpWeight;
                                                      } else if (index == 14) {
                                                        dataList[index] =
                                                            cardModel.UseWeight;
                                                      } else if (index == 15) {
                                                        dataList[index] =
                                                            cardModel
                                                                .YearEndTime;
                                                      } else if (index == 16) {
                                                        dataList[index] =
                                                            cardModel
                                                                .CarEndTime;
                                                      } else if (index == 17) {
                                                        dataList[index] =
                                                            cardModel.CardNum;
                                                      } else if (index == 18) {
                                                        dataList[index] =
                                                            cardModel.OutLength;
                                                      } else if (index == 19) {
                                                        dataList[index] =
                                                            cardModel.OutWidth;
                                                      } else if (index == 20) {
                                                        dataList[index] =
                                                            cardModel.OutHeight;
                                                      }
                                                      _nametextEditingController
                                                          .text =
                                                      dataList[index];
                                                    });
                                                  },
                                                    child: Text(
                                                      messages["确定"],
                                                      style: TextStyle(
                                                          color: Color.fromRGBO(
                                                              231, 112, 27,
                                                              0.85),
                                                          fontSize: 14.sp),),),
                                                ],
                                              ),
                                              SizedBox(height: 8.h,),
                                              Container(

                                                margin: EdgeInsets.only(
                                                    left: 18.w,
                                                    right: 18.w),
                                                decoration: BoxDecoration(
                                                  borderRadius: BorderRadius
                                                      .circular(30.0),

                                                ),
                                                child: TextField(

                                                    controller: _nametextEditingController,
                                                    keyboardType: (index==12||index==13||index==14)?TextInputType.number: TextInputType.text,

                                                    style: TextStyle(
                                                      color: Colors.black,),
                                                    decoration: InputDecoration(
                                                      filled: true,
                                                      fillColor: Color.fromRGBO(
                                                          249, 249, 249, 1),
                                                      border: InputBorder.none,

                                                    ),
                                                    onChanged: (text) {
                                                      setState(() {
                                                        if (index == 0) {
                                                          cardModel.CarNum =
                                                              text;
                                                          print(
                                                              cardModel.CarNum);
                                                        } else if (index == 1) {
                                                          cardModel.CarColor =
                                                              text;
                                                        } else if (index == 2) {
                                                          cardModel
                                                              .LengthWeight =
                                                              text;
                                                        } else if (index == 3) {
                                                          cardModel.CarStyle =
                                                              text;
                                                        } else if (index == 4) {
                                                          cardModel.KnowNum =
                                                              text;
                                                        } else if (index == 5) {
                                                          cardModel.UseStyle =
                                                              text;
                                                        } else if (index == 6) {
                                                          cardModel.AddTime =
                                                              text;
                                                        } else if (index == 7) {
                                                          cardModel.OfficeTime =
                                                              text;
                                                        } else if (index == 8) {
                                                          cardModel
                                                              .CardOfficeName =
                                                              text;
                                                        } else if (index == 9) {
                                                          cardModel.CarUser =
                                                              text;
                                                        } else
                                                        if (index == 10) {
                                                          cardModel.MessageNum =
                                                              text;
                                                        } else
                                                        if (index == 11) {
                                                          cardModel.OilStyle =
                                                              text;
                                                        } else
                                                        if (index == 12) {
                                                          cardModel.AllWeight =
                                                              text;
                                                        } else
                                                        if (index == 13) {
                                                          cardModel.UpWeight =
                                                              text;
                                                        } else
                                                        if (index == 14) {
                                                          cardModel.UseWeight =
                                                              text;
                                                        } else
                                                        if (index == 15) {
                                                          cardModel
                                                              .YearEndTime =
                                                              text;
                                                        } else
                                                        if (index == 16) {
                                                          cardModel.CarEndTime =
                                                              text;
                                                        } else
                                                        if (index == 17) {
                                                          cardModel.CardNum =
                                                              text;
                                                        } else
                                                        if (index == 18) {
                                                          cardModel.OutLength =
                                                              text;
                                                        } else
                                                        if (index == 19) {
                                                          cardModel.OutWidth =
                                                              text;
                                                        } else
                                                        if (index == 20) {
                                                          cardModel.OutHeight =
                                                              text;
                                                        }
                                                      });
                                                    }
                                                ),
                                              ),

                                            ],
                                          ),
                                        );
                                      });
                                }
                              }
                            }
                        ),
                      );
                    }
                ),
              ),


            ],
          ),

          ),
          Container(
            height: 80.h,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  height: 40.h ,
                  margin: EdgeInsets.only(left: 30.w,right: 30.w),
                  decoration: BoxDecoration(
                      color:MyColors.themeColor,
                      borderRadius: BorderRadius.all(Radius.circular(30))),

                  width: double.infinity,


                  child: TextButton(
                      child: Text(isEdit?"添加":"编辑",style: TextStyle(color: Colors.white,fontSize: 14.sp,fontWeight: FontWeight.w600),),

                      onPressed: () async {
                        if (isEdit == false) {
                          setState(() {
                            isEdit = true;
                          });
                        } else {
                          isShowError=true;
                          if (dataList[0] == "") {
                            BrnToast.show("请输入车牌号", context,
                              duration: BrnDuration.short,);
                          }else if(!isCarNumber(dataList[0])){
                            BrnToast.show(
                              "请输入正确的车牌号", context, duration: BrnDuration
                                .short,);
                          }
                          else if (dataList[3] == "") {
                            BrnToast.show("请输入车辆类型", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[4] == "") {
                            BrnToast.show("请输入车辆识别代号", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[5] == "") {
                            BrnToast.show(
                              "请输入使用性质", context, duration: BrnDuration
                                .short,);
                          }
                          else if (dataList[6] == "") {
                            BrnToast.show(
                              "请选择注册日期", context, duration: BrnDuration
                                .short,);
                          }
                          else if (dataList[7] == "") {
                            BrnToast.show("请选择发证日期", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[8] == "") {
                            BrnToast.show("请输入发证机关", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[9] == "") {
                            BrnToast.show("请输入车辆所有人", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[10] == "") {
                            BrnToast.show("请输入档案编号", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[11] == "") {
                            BrnToast.show("请选择能源类型", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[12] == "") {
                            BrnToast.show("请输入总质量", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[13] == "") {
                            BrnToast.show("请输入整备质量", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[14] == "") {
                            BrnToast.show("请输入核定载质量", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[15] == "") {
                            BrnToast.show("请选择年审有效期", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[16] == "") {
                            BrnToast.show("请选择强制报废截止日", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[17] == "") {
                            BrnToast.show("请输入证芯编号", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[18] == "") {
                            BrnToast.show("请输入外廓车长", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[19] == "") {
                            BrnToast.show("请输入外廓车宽", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[20] == "") {
                            BrnToast.show("请输入外廓车高", context,
                              duration: BrnDuration.short,);
                          }
                          else if (getbackPath == "" || getfrontPath == "") {
                            BrnToast.show("请添加行驶证图片", context,
                              duration: BrnDuration.short,);
                          }
                          else {
                            String? drvId = await UserIdManager.getUserID();
                            ApiManager.postData(
                              context,
                              'api/auth/driver/vehicle/editVehicleTrailerDrivingLicenseInfoByCaptain',
                              {
                                "vehicleId":widget.dataMap['id'],
                                "driverId": drvId,
                                "vin": dataList[4],
                                "owner": dataList[9],
                                "fileNum": dataList[10],
                                "backPath": getbackPath,
                                "frontPath": getfrontPath,
                                "grossMass": dataList[12],
                                "issueDate": dataList[7],
                                "scrapDate": dataList[16],
                                "expiryDate": dataList[15],
                                "vehicleNum": dataList[0],
                                "vehicleNumColor": dataList[1] == "黄色" ? "2"
                                    : dataList[1] == "蓝色"
                                    ? "1"
                                    : dataList[1] ==
                                    "绿色" ? "5" : dataList[1] == "黄绿色"
                                    ? "93"
                                    : "9",
                                "vehicleModel": carType,
                                "vehicleLength": carLength,
                                "vehicleCurbWeight": dataList[13],
                                "vehicleType": dataList[3],
                                "registerDate": dataList[6],
                                "useCharacter": dataList[5],
                                "overallHigh": dataList[20],
                                "overallWide": dataList[19],
                                "overallLength": dataList[18],
                                "vehicleTonnage": dataList[14],
                                "vehicleEnergyType": dataList[11],
                                "certificateCoreNum": dataList[17],
                                "issuingOrganizations": dataList[8]
                              },
                                  (responseData) {
                                BrnToast.show("添加成功", context,
                                  duration: BrnDuration.short,);
                                Navigator.pop(context, "success");
                              },
                            );
                          }
                        }
                      }
                  ),
                ),
              ],
            ),
          ),



          // }),

        ],
      ),



    );
  }
}
